import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter登录表单示例',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const LoginPage(),
    );
  }
}

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 创建表单的全局键，用于获取表单状态
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  
  // 创建焦点节点，用于控制输入框的焦点
  final FocusNode _userFocusNode = FocusNode();
  final FocusNode _passwordFocusNode = FocusNode();
  
  // 用于存储输入的值
  String? _user;
  String? _password;
  bool _obscureText = true; // 控制密码是否可见
  bool _agreedToTerms = false; // 新增：用户是否同意条款
  
  @override
  void dispose() {
    // 释放焦点节点资源
    _userFocusNode.dispose();
    _passwordFocusNode.dispose();
    super.dispose();
  }
  
  // 切换密码可见性
  void _togglePasswordVisibility() {
    setState(() {
      _obscureText = !_obscureText;
    });
  }
  
  // 提交表单
  void _submitForm() {
    // 验证表单
    if (_formKey.currentState!.validate()) {
      // 如果验证通过，则保存表单值
      _formKey.currentState!.save();
      
      // 这里可以执行登录逻辑
      print('登录信息 - 账号: $_user, 密码: $_password');
      
      // 显示登录成功的提示
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('登录成功！')),
      );
    }
  }
  
  // 移动焦点到下一个输入框
  void _fieldFocusChange(BuildContext context, FocusNode currentFocus, FocusNode nextFocus) {
    currentFocus.unfocus();
    FocusScope.of(context).requestFocus(nextFocus);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录表单示例'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // 用户输入框
              TextFormField(
                focusNode: _userFocusNode,
                decoration: const InputDecoration(
                  labelText: '账号',
                  hintText: '请输入电话号码或邮箱',
                  prefixIcon: Icon(Icons.verified_user),
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.emailAddress,
                textInputAction: TextInputAction.next,
                // 用户验证
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '账号不能为空';
                  }
                // 格式验证
                  if(value.length!=11){
                    if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
                    return '请输入有效的电话号码或邮箱';
                    }
                  }
                  return null;
                },
                // 保存用户值
                onSaved: (value) {
                  _user = value;
                },
                // 按下一步时移动焦点到密码框
                onFieldSubmitted: (value) {
                  _fieldFocusChange(context, _userFocusNode, _passwordFocusNode);
                },
              ),
              
              const SizedBox(height: 16.0),
              
              // 密码输入框
              TextFormField(
                focusNode: _passwordFocusNode,
                decoration: InputDecoration(
                  labelText: '密码',
                  hintText: '请输入您的密码',
                  prefixIcon: const Icon(Icons.lock),
                  suffixIcon: IconButton(
                    icon: Icon(
                      _obscureText ? Icons.visibility : Icons.visibility_off,
                    ),
                    onPressed: _togglePasswordVisibility,
                  ),
                  border: const OutlineInputBorder(),
                ),
                obscureText: _obscureText,
                textInputAction: TextInputAction.done,
                // 密码验证
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入密码';
                  }
                  if (value.length < 6) {
                    return '密码长度至少需要6个字符';
                  }
                  return null;
                },
                // 保存密码值
                onSaved: (value) {
                  _password = value;
                },
                // 按完成时提交表单
                onFieldSubmitted: (value) {
                  _passwordFocusNode.unfocus();
                  _submitForm();
                },
              ),
              
              const SizedBox(height: 16.0),
              
              // 新增：用户协议复选框
              Row(
                children: [
                  Checkbox(
                    value: _agreedToTerms,
                    onChanged: (bool? value) {
                      setState(() {
                        _agreedToTerms = value ?? false;
                      });
                    },
                  ),
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        // 点击文本也能切换复选框状态
                        setState(() {
                          _agreedToTerms = !_agreedToTerms;
                        });
                      },
                      child: RichText(
                        text: TextSpan(
                          style: TextStyle(color: Colors.grey[700]),
                          children: [
                            const TextSpan(text: '我已阅读并同意'),
                            TextSpan(
                              text: '用户协议',
                              style: const TextStyle(color: Colors.blue),
                              // 这里可以添加点击事件处理用户协议页面跳转
                              recognizer: null, // 实际项目中添加点击处理
                            ),
                            const TextSpan(text: '和'),
                            TextSpan(
                              text: '隐私政策',
                              style: const TextStyle(color: Colors.blue),
                              // 这里可以添加点击事件处理隐私政策页面跳转
                              recognizer: null, // 实际项目中添加点击处理
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              
              const SizedBox(height: 24.0),
              
              // 登录按钮
              ElevatedButton(
                onPressed: _agreedToTerms ? _submitForm : null, // 只有同意条款才能点击
                child: const Padding(
                  padding: EdgeInsets.symmetric(vertical: 12.0),
                  child: Text(
                    '登录',
                    style: TextStyle(fontSize: 16.0),
                  ),
                ),
              ),
              
              const SizedBox(height: 16.0),
              
              // 辅助按钮：获取焦点示例
              TextButton(
                onPressed: () {
                  FocusScope.of(context).requestFocus(_passwordFocusNode);
                },
                child: const Text('移动焦点'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}